package com.example.demo.controller.train;
import java.util.Date;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.base.config.auth.UserInfoShareHolder;
import com.example.demo.base.login.dto.UserCache;
import com.example.demo.common.BusinessStateCode;
import com.example.demo.domain.entity.TrainClassHomework;
import com.example.demo.domain.entity.User;
import com.example.demo.domain.model.ClassUserCount;
import com.example.demo.domain.vo.TrainClassVo;
import com.example.demo.enums.TrainClassStatusEnum;
import com.example.demo.service.TrainClassUserService;
import com.example.demo.service.UserService;
import com.example.demo.utils.BeanCopyUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.example.demo.domain.entity.TrainClass;
import com.example.demo.domain.model.TrainClassForm;
import com.example.demo.dto.PageDto;
import com.example.demo.dto.ResponseDto;
import com.example.demo.param.TrainClassParam;
import com.example.demo.service.TrainClassService;
import com.tencentcloudapi.tci.v20190318.models.Person;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * 培训-班级
 */
@Controller
@Slf4j
@RequestMapping("/train/train-class")
public class TrainClassController {

    @Resource
    private TrainClassService trainClassService;

    @Resource
    private TrainClassUserService trainClassUserService;


    @Resource
    private UserService userService;



    /**
     * 创建培训班级
     * @param form
     * @return
     */
    @RequestMapping("/create")
    @ResponseBody
    public ResponseDto createTrainClass(@RequestBody TrainClassForm form) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null || form == null) {
            return new ResponseDto<>().buildFail("未登录或参数异常");
        }
        if (StringUtils.isBlank(form.getName().trim())){
            return new ResponseDto().buildFail("班级名不规范");
        }
        log.info("创建培训班级参数:{}", JSONUtil.toJsonStr(form));
        //人维度查询班级
        List<TrainClass> trainClass = trainClassService.queryTrainClassByNameAndUserId(form.getName(), userInfo.getUser().getId());
        if (CollectionUtils.isNotEmpty(trainClass)) {
            return new ResponseDto().buildFail("已存在同名班级");
        }
        form.setBelongTeacherId(userInfo.getUser().getId());
        form.setCompanyId(userInfo.getCompanyId());
        form.setCreator(userInfo.getUser().getId());
        Boolean result = trainClassService.insertTrainClass(form);
        if (!result) {
           return new ResponseDto<>().buildFail();
        }
        return new ResponseDto<>().buildSucceed();
    }



    /**
     * 修改培训班级信息
     * @param form
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public ResponseDto updateTrainClass(@RequestBody TrainClassForm form) {
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null || form == null) {
            return new ResponseDto<>().buildFail("未登录或参数异常");
        }
        if (StringUtils.isBlank(form.getName().trim())){
            return new ResponseDto().buildFail("已存在同名班级");
        }
        //人维度查询班级
        List<TrainClass> trainClassTmp = trainClassService.queryTrainClassByNameAndUserId(form.getName(), userInfo.getUser().getId());
        if (CollectionUtils.isNotEmpty(trainClassTmp)) {
            return new ResponseDto().buildFail("已存在同名班级");
        }
        TrainClass trainClass = trainClassService.getById(form.getTrainClassId());
        if (trainClass == null || !trainClass.getCompanyId().equals(userInfo.getCompanyId())) {
            return new ResponseDto().buildFail("无权限操作");
        }
        trainClass.setName(form.getName());
        trainClass.setNotes(form.getNotes());
        trainClass.setUpdateTime(new Date());
        trainClass.setUpdatorId(userInfo.getUser().getId());
        log.info("更新培训班级参数:{}", JSONUtil.toJsonStr(form));
        boolean result = trainClassService.updateById(trainClass);
        if (!result) {
            return new ResponseDto<>().buildFail();
        }
        return new ResponseDto<>().buildSucceed();
    }


    /**
     * 获取培训班级-
     * @return
     */
    @RequestMapping("/page-all")
    @ResponseBody
    public ResponseDto<PageDto<TrainClassVo>> all(@RequestBody TrainClassParam param){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (param.getBelongTeacherId() == null && param.getCompanyId() == null){
            param.setBelongTeacherId(userInfo.getUser().getId());
        }
        Page<TrainClass> result = trainClassService.queryTrainClass(param);
        List<TrainClass> records = result.getRecords();
        List<TrainClassVo> trainClassVos = BeanCopyUtil.copyListProperties(records, TrainClassVo::new);
        List<Long> collect = trainClassVos.stream().map(TrainClassVo::getBelongTeacherId).collect(Collectors.toList());
        Map<Long, User> longUserMap = userService.queryByIds(collect);

        for (TrainClassVo trainClassVo : trainClassVos) {
            User user = longUserMap.get(trainClassVo.getBelongTeacherId());
            trainClassVo.setTeacherName(user != null ? user.getUsername() : "");
        }
        PageDto<TrainClassVo> resultVo = new PageDto<>();
        resultVo.setPage(param.getPageNumber());
        resultVo.setSize(param.getPageSize());
        resultVo.setTotal(result.getTotal());
        resultVo.setList(trainClassVos);
        return new ResponseDto<PageDto<TrainClassVo>>().buildSucceedHasData(resultVo);
    }


    /**
     * 获取自己公司的所有班级-不分页查询 只这个接口查询班级人数
     * @return
     */
    @RequestMapping("/all")
    @ResponseBody
    public ResponseDto<List<TrainClassVo>> all(){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        List<TrainClass> trainClasses = trainClassService.queryAllTrainClassByCompanyId(userInfo.getCompanyId());
        if (CollectionUtils.isEmpty(trainClasses)){
            return new ResponseDto().buildSucceed();
        }
        List<TrainClassVo> trainClassVos = BeanCopyUtil.copyListProperties(trainClasses, TrainClassVo::new);
        List<Long> collect = trainClassVos.stream().map(TrainClassVo::getId).collect(Collectors.toList());
        List<ClassUserCount> classUserCounts = trainClassUserService.countNumber(collect);
        Map<Long, Integer> maps = classUserCounts.stream().collect(Collectors.toMap(ClassUserCount::getClassId, ClassUserCount::getUserCount));
        List<TrainClassVo> collect1 = trainClassVos.stream().filter(trainClassVo -> maps.get(trainClassVo.getId()) != null && maps.get(trainClassVo.getId()) > 0).collect(Collectors.toList());
        collect1.forEach(trainClassVo -> trainClassVo.setNumberCount(maps.get(trainClassVo.getId())));
        return new ResponseDto<List<TrainClassVo>>().buildSucceedHasData(collect1);
    }


    /**
     * 把班级分配给某一个老师
     * @return
     *//*
    @RequestMapping("/assignment/teacher")
    @ResponseBody
    public ResponseDto<Boolean> assignmentTrainClass(Long trainClassId, Long teacherId){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (userInfo == null || trainClassId == null || teacherId == null) {
            return new ResponseDto<Boolean>().buildFail("未登录或参数错误");
        }
        TrainClass trainClass = trainClassService.getById(trainClassId);
        if (trainClass == null) {
            return new ResponseDto<Boolean>().buildFail("无对应班级");
        }
        trainClass.setBelongTeacherId(teacherId);
        boolean result = trainClassService.updateById(trainClass);
        return new ResponseDto<Boolean>().buildSucceedHasData(result);
    }*/


    /**
     * 获取邀请码
     * @param id
     * @return
     */
    @RequestMapping("/get/inviteCode/{id}")
    @ResponseBody
    public ResponseDto<String> getInviteCode(@PathVariable("id") Long id){
        if (id == null || id <= 0){
            return new ResponseDto<String>().buildFailResponse(BusinessStateCode.VALIDATE_ERROR);
        }
        TrainClass result = trainClassService.getById(id);
        if (result == null) {
            return new ResponseDto<String>().buildFail();
        }
        return new ResponseDto<String>().buildSucceedHasData(result.getInviteCode());
    }

    /**
     * 关闭班级
     * @param id
     * @return
     */
    @RequestMapping("/close/train-class/{id}")
    @ResponseBody
    public ResponseDto<Boolean> closeTrainClass(@PathVariable("id") Long id){
        UserCache userInfo = UserInfoShareHolder.getUserInfo();
        if (id == null || id <= 0 || userInfo == null){
            return new ResponseDto<Boolean>().buildFailResponse(BusinessStateCode.VALIDATE_ERROR);
        }
        TrainClass trainClass = trainClassService.getById(id);
        if (trainClass == null) {
            return new ResponseDto<Boolean>().buildFail("无对应班级");
        }
        trainClass.setStatus(TrainClassStatusEnum.DISABLE.getKey());
        boolean result = trainClassService.updateById(trainClass);
        return new ResponseDto<Boolean>().buildSucceedHasData(result);
    }


    /**
     * 根据公司id 获取培训师-分配给某个老师使用
     * @param companyId 公司id
     * @return
     */
    /*@RequestMapping("/all-teacher")
    @ResponseBody
    public ResponseDto<List<User>> getAllTeacher(Long companyId){

        List<User> result = new ArrayList<>();


        return new ResponseDto<List<User>>().buildSucceedHasData(result);
    }*/


    /**
     * 培训班级移除某一个学生
     * @param trainClassId 培训班级id
     * @param userId    用户id
     * @return
     */
    @RequestMapping("/remove-user")
    @ResponseBody
    public ResponseDto<Boolean> removeUser(Long trainClassId, Long userId){
        boolean result = trainClassUserService.removeUser(trainClassId, userId);
        return new ResponseDto<Boolean>().buildSucceedHasData(result);
    }
















}
